package cn.tjad.tjad2.module.material.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.widget.TJADTTitleView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.Id;
import cn.tjad.tjad2.data.bean.MaterialDetail;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.data.event.MaterialItemCheckedEvent;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;
import cn.tjad.tjad2.module.material.adapter.MaterialDetailAdapter;
import cn.tjad.tjad2.module.material.bean.request.AsignRequestBean;
import cn.tjad.tjad2.module.material.bean.request.ItemRequestBean;
import cn.tjad.tjad2.module.user.userselect.SelectMode;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.ProgressDialogUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;
import io.reactivex.functions.Consumer;

@Route(path = PageId.MATERIAL_DETAIL)
public class MaterialDetailFragment extends BaseFragment implements OnRefreshListener {

    @BindView(R.id.material_detail_steps)
    TextView filterByStepBtn;
    @BindView(R.id.material_detail_related)
    TextView filterByRelatedBtn;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.material_detail_transfer)
    TextView transferBtn;
    @BindView(R.id.material_detail_update)
    TextView updateBtn;
    @BindView(R.id.material_detail_back)
    TextView backBtn;
    @BindView(R.id.material_detail_operate_layout)
    View operateView;

    private int materialId;
    private MaterialDetailAdapter adapter;
    private MaterialDetail materialDetail;

    private final int OP_TRANSFER = 3001;
    private final int OP_UPDATE = 3002;
    private final int OP_BACK = 3003;

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.material_detail, null);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            materialId = getArguments().getInt(Keys.MATERIAL_ID, -1);
        }
        if (materialId == -1) {
            Tools.showToast("必须传入有效的materialId");
            return;
        }
        operateView.setVisibility(View.GONE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        adapter = new MaterialDetailAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.autoRefresh();
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.setCenterText("清单列表");
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestMaterialDetail();
    }

    private void requestMaterialDetail() {
        RetrofitManager.getInstance()
                .getApiService()
                .getMaterialTrackingDetail(Tools.getProjectId(), materialId)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<MaterialDetail>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<MaterialDetail> t) {
                        onMaterialDetailReceived(t.result);
                        refreshLayout.finishRefresh(true);
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        refreshLayout.finishRefresh(false);
                    }
                });
    }

    private void onMaterialDetailReceived(MaterialDetail result) {
        this.materialDetail = result;
        adapter.updateData(result.items);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onMaterialItemCheckedEvent(MaterialItemCheckedEvent event) {
        List<MaterialDetail.Item> itemList = adapter.getData();
        boolean showOperate = false;
        if (itemList != null && itemList.size() > 0) {
            for (MaterialDetail.Item item: itemList) {
                if (item.isChecked) {
                    showOperate = true;
                    break;
                }
            }
        }
        if (showOperate) {
            operateView.setVisibility(View.VISIBLE);
        } else {
            operateView.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.material_detail_transfer, R.id.material_detail_update, R.id.material_detail_back})
    public void onOperateClick(View view) {
        switch (view.getId()) {
            case R.id.material_detail_transfer:
                transferMaterialItem();
                break;
            case R.id.material_detail_update:
                doUpdateConfirm();
                break;
            case R.id.material_detail_back:
                doBackConfirm();
                break;
        }
    }

    private void transferMaterialItem() {
        List<Id> ids = getCheckedItems();
        if (getCheckedItems().size() == 0) {
            Tools.showToast("请勾选需要操作的项目");
        } else {
            SelectMode.setSelectMode(SelectMode.SINGGLE_CHOICE);
            RouteUtils.toPageForResult((Activity) getContext(), PageId.USER_SELECT_2, null, OP_TRANSFER);
        }
    }

    private List<Id> getCheckedItems() {
        List<MaterialDetail.Item> itemList = adapter.getData();
        List<Id> ids = new ArrayList<>();
        if (itemList != null && itemList.size()> 0) {
            for (MaterialDetail.Item item: itemList) {
                if (item.isChecked) {
                    Id id = new Id();
                    id.id = item.id;
                    ids.add(id);
                }
            }
        }
        return ids;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == OP_TRANSFER) {
                ArrayList<User> selectedUsers = (ArrayList<User>) data.getSerializableExtra(Keys.SELECTED_RESULTS);
                User selectedUser = selectedUsers.get(0);
                List<Id> selectedItems = getCheckedItems();
                doTransferConfirm(selectedItems, selectedUser);
            }
        }
    }

    private void doTransferConfirm(List<Id> selectedItems, User user) {
        if (selectedItems == null || user == null || selectedItems.size() == 0) {
            return;
        }
        TjDialogFragment dialogFragment = new TjDialogFragment.Builder(getContext())
                .setTitle("转交确认")
                .setMessage("是否确认将选中的物料转交给" + user.name + "?")
                .setPositiveButton("确认转交", (dialog, which) -> {
                    doTransfer(selectedItems, user);
                    return true;
                })
                .setNegativeButton("取消", null)
                .create();
        dialogFragment.show(getChildFragmentManager(), "materialTransfer");
    }

    private void doTransfer(List<Id> selectedItems, User user) {
        AsignRequestBean requestBean = new AsignRequestBean();
        requestBean.items = (ArrayList<Id>) selectedItems;
        requestBean.responsibleUserId = user.id;
        RetrofitManager.getInstance().getApiService()
                .asignMaterial(Tools.getProjectId(), materialId, requestBean)
                .compose(RxUtils.networkTransformer())
                .doOnNext(baseBeanCommonBean -> ProgressDialogUtils.show(getContext(), "正在转交..."))
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        ProgressDialogUtils.dismiss();
                        Tools.showToast("转交成功");
                        refreshLayout.autoRefresh();
                    }

                    @Override
                    public void onFailed(String message) {
                        ProgressDialogUtils.dismiss();
                        if (TextUtils.isEmpty(message)) {
                            Tools.showToast("转交失败");
                        } else {
                            Tools.showToast(message);
                        }
                    }
                });
    }

    private void doUpdateConfirm() {
        List<Id> selectedItems = getCheckedItems();
        if (selectedItems == null || selectedItems.size() == 0) {
            return;
        }
        TjDialogFragment dialogFragment = new TjDialogFragment.Builder(getContext())
                .setTitle("更新确认")
                .setMessage("是否确认更新所选物料？")
                .setPositiveButton("确认更新", (dialog, which) -> {
                    doUpdate(selectedItems);
                    return true;
                })
                .setNegativeButton("取消", null)
                .create();
        dialogFragment.show(getChildFragmentManager(), "materialUpdate");
    }

    private void doUpdate(List<Id> selectedItems) {
        ItemRequestBean requestBean = new ItemRequestBean();
        requestBean.items = (ArrayList<Id>) selectedItems;
        RetrofitManager.getInstance()
                .getApiService()
                .updateMaterial(Tools.getProjectId(), materialId, requestBean)
                .compose(RxUtils.networkTransformer())
                .doOnNext(baseBeanCommonBean -> ProgressDialogUtils.show(getContext(), "正在更新..."))
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        ProgressDialogUtils.dismiss();
                        Tools.showToast("更新成功");
                        refreshLayout.autoRefresh();
                    }

                    @Override
                    public void onFailed(String message) {
                        ProgressDialogUtils.dismiss();
                        if (TextUtils.isEmpty(message)) {
                            Tools.showToast("更新失败");
                        } else {
                            Tools.showToast(message);
                        }
                    }
                });
    }

    private void doBackConfirm() {
        List<Id> selectedItems = getCheckedItems();
        if (selectedItems == null || selectedItems.size() == 0) {
            return;
        }
        TjDialogFragment dialogFragment = new TjDialogFragment.Builder(getContext())
                .setTitle("退回确认")
                .setMessage("是否确认退回所选物料？")
                .setPositiveButton("确认退回", (dialog, which) -> {
                    doBack(selectedItems);
                    return true;
                })
                .setNegativeButton("取消", null)
                .create();
        dialogFragment.show(getChildFragmentManager(), "materialBack");
    }

    private void doBack(List<Id> selectedItems) {
        ItemRequestBean requestBean = new ItemRequestBean();
        requestBean.items = (ArrayList<Id>) selectedItems;
        RetrofitManager.getInstance()
                .getApiService()
                .backMaterial(Tools.getProjectId(), materialId, requestBean)
                .compose(RxUtils.networkTransformer())
                .doOnNext(baseBeanCommonBean -> ProgressDialogUtils.show(getContext(), "正在退回..."))
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        ProgressDialogUtils.dismiss();
                        Tools.showToast("退回成功");
                        refreshLayout.autoRefresh();
                    }

                    @Override
                    public void onFailed(String message) {
                        ProgressDialogUtils.dismiss();
                        if (TextUtils.isEmpty(message)) {
                            Tools.showToast("退回失败");
                        } else {
                            Tools.showToast(message);
                        }
                    }
                });
    }
}
